// 优惠卷管理
<template>
  <div class="role">
     <div class="role-content">
        <div class="role-top">
            <el-input placeholder="请输入优惠券标题" v-model="paging.title" clearable></el-input>
            <el-select v-model="paging.type" placeholder="请选择优惠券类型" style="margin-right: 10px;">
                    <el-option
                    v-for="item in discounts"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                    </el-option>
                </el-select>
             <el-select v-model="paging.status" placeholder="请选择优惠券状态" style="margin-right: 10px;">
                    <el-option
                    v-for="item in statelist"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                    </el-option>
              </el-select>
              <el-button type="primary" icon="el-icon-search" @click="role">搜索</el-button>
              <el-button type="primary" icon="el-icon-edit" @click="addEquipment()">添加</el-button>   
              <el-button type="primary" icon="el-icon-download" @click="export2Excel()">当前页导出</el-button>    
        </div>
        <!--内容 -->
        <el-card class="box-card">
            <DataTable :data='listData' :column='tablecolumn'>
               <el-table-column label="操作" width='300px'>
                    <template slot-scope="scope">
                        <el-button size="mini"  @click="freezeActivate(scope.row)" class="blue">{{scope.row.status<0?'已过期':scope.row.status==1?'激活':'冻结'}}</el-button>
                        <el-button size="mini"  @click="handelEdit(scope.row)" class="blue">编辑</el-button>
                        <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </DataTable>
             <!-- <el-table :data="listData" style="width:100%" border>
                <el-table-column  prop="id" label="优惠卷id"  sortable   > </el-table-column>
                <el-table-column prop="title" label="优惠卷名称"  > </el-table-column>
                <el-table-column prop="type" label="优惠卷类型"  ><template slot-scope="scope">{{scope.row.type==1?'满减卷':''}}</template></el-table-column>
                <el-table-column prop="description" label="介绍"  > </el-table-column>
                <el-table-column prop="total" label="优惠卷数量"  > </el-table-column>
                <el-table-column prop="surplus" label="剩余数量"  > </el-table-column>
                <el-table-column prop="surplus" label="每人限领"  > </el-table-column>
                <el-table-column prop="discount" label="满减金额"  >
                  <template slot-scope="scope">
                     满免{{scope.row.discount}}元
                  </template>
                </el-table-column>
                <el-table-column prop="min" label="最底消费">
                    <template slot-scope="scope">
                     满{{scope.row.min}}可用
                  </template>
                </el-table-column>
                <el-table-column prop="status" label="状态">
                  <template slot-scope="scope">
                      <el-tag>{{scope.row.status|gmtStarts(scope.row.gmtEnd)}}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="categoryTitle" label="使用类目名称"  >
                    <template slot-scope="scope">
                        <el-tag>{{scope.row.categoryTitle|categorysTitles()}}</el-tag>
                    </template>
                 </el-table-column>
                <el-table-column prop="categoryId" label="使用类目id"  > </el-table-column>
                <el-table-column prop="days" label="领卷相对天数"  > </el-table-column>
                <el-table-column prop="gmtStart" label="领卷开始时间">
                    <template slot-scope="scope">
                        {{scope.row.gmtStart|formatDate()|timeDate()}}
                    </template>    
                 </el-table-column>
                <el-table-column prop="gmtEnd" label="领卷结束时间"> 
                    <template slot-scope="scope">
                        {{scope.row.gmtEnd|formatDate()|timeDate()}}
                    </template>  
                </el-table-column>
                <el-table-column label="操作" width='300px'>
                    <template slot-scope="scope">
                        <el-button size="mini"  @click="freezeActivate(scope.row)" class="blue">{{scope.row.status<0?'已过期':scope.row.status==1?'激活':'冻结'}}</el-button>
                        <el-button size="mini"  @click="handelEdit(scope.row)" class="blue">编辑</el-button>
                        <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table> -->
        </el-card>
        <!-- 分页 -->
        <div class="block">
        <!-- current-change当前页size-change每页条数current-page当前页数，支持 .sync 修饰符page-sizes每页显示条目个数，支持 .sync 修饰符-->
        <Paging @handle="handles" :allPages="paging"></Paging>
      </div>
        <!-- 添加编辑 -->
        <el-dialog :title="titleMap[dialogStatus]" :visible.sync="dialogFormVisible">
            <el-form :model="ruleForm" ref="ruleForm" :rules="rules">
            <el-form-item label="优惠券名称" prop='title' :label-width="formLabelWidth">
              <el-input v-model="ruleForm.title" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="优惠卷类型"  :label-width="formLabelWidth" >
                <el-select v-model="ruleForm.type" placeholder="请选择">
                    <el-option
                    v-for="item in discounts"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
          <el-form-item label="介绍"  prop='name' :label-width="formLabelWidth">
            <el-input v-model="ruleForm.description" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="优惠券数量"  prop='total' :label-width="formLabelWidth">
            <el-input placeholder="请输入内容" v-model="ruleForm.total">
               <template slot="append">张</template>
            </el-input>
          </el-form-item>
          <el-form-item label="每人限领"  prop='limit' :label-width="formLabelWidth">
            <el-input placeholder="请输入内容" v-model="ruleForm.limit">
               <template slot="append">张</template>
            </el-input>
          </el-form-item>
          <el-form-item label="满减金额"  prop='discount' :label-width="formLabelWidth">
            <el-input placeholder="请输入内容" v-model="ruleForm.discount">
               <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="最低消费"  prop='min' :label-width="formLabelWidth">
            <el-input placeholder="请输入内容" v-model="ruleForm.min">
               <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="优惠卷状态"  :label-width="formLabelWidth" >
                <el-select v-model="ruleForm.status" placeholder="请选择" >
                    <el-option
                    v-for="item in statelist"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="有效期"  :label-width="formLabelWidth" >
                <div>
                <el-button class="validtime" @click="conceals" :class="conceal==false?'validtimes':''">领券相对天数</el-button>
                <el-button class="validtime" @click="conceals" style="margin-left: 0px !important;" :class="conceal==true?'validtimes':''">指定绝对时间</el-button>
              </div>
              <div class="validtime_nane">
                <el-input placeholder="请输入内容" v-model="ruleForm.days" v-show="!conceal">
                  <template slot="append">天</template>
                </el-input>
                <div class="block" v-show="conceal">
                  <el-date-picker
                    v-model="ruleForm.time"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期">
                  </el-date-picker>
                </div>
              </div>
            </el-form-item>
            <el-form-item label="商品限制范围"  :label-width="formLabelWidth" >
                <div>
                <el-button class="validtime" @click="concealList" :class="conceallist==false?'validtimes':''" :disabled="state">全场通用</el-button>
                <el-button class="validtime" @click="concealList" style="margin-left: 0px !important;" :disabled="state" :class="conceallist==true?'validtimes':''">指定分类</el-button>
              </div>
              <div class="validtime_nane" v-show="conceallist">
                <el-cascader ref="cascader" :options="options" v-model="ruleForm.categoryId" @change="handleChange" placeholder="关联产品"></el-cascader>
              </div>
            </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="affirm(ruleForm)">确 定</el-button>
            </div>
        </el-dialog>
     </div>
  </div>
</template>
<script>
import Couponmanage from'../../api/promotion/couponmanage'
export default {
components: {
    Paging:() => import('../../components/Paging'),
    DataTable:() => import('@/components/table')
  },
  data() {
    return {
      tablecolumn:[
        {
          label:'优惠券ID',
          prop:'id',
          sortable:true
        },
        {
          label:'2',
          prop:'title',
          sortable:true
        },
        {
          label:'3',
          prop:'type',
          sortable:true
        },
        {
          label:'4',
          prop:'description',
          sortable:true
        },
        {
          label:'5',
          prop:'total',
          sortable:true
        },
        {
          label:'6',
          prop:'surplus',
          sortable:true
        },
        {
          label:'7',
          prop:'discount',
          sortable:true
        },
        {
          label:'8',
          prop:'gmtEnd',
          sortable:true,
          type:'time',
          timetype:'yyyy-mm-dd'
        },
        {
          label:'9',
          prop:'categoryTitle',
          sortable:true,
          type:'tag'
          
        },
        {
          label:'10',
          prop:'min',
          sortable:true,
          type:'sorttext',
          soltcontent:"满减sort元"
          
        }
      ],
      // 禁止按钮状态
      state :false,
      conceal:false,
      conceallist:false,
      options:[],//级联
      statelist:[{//状态类型
        value:'1',
        label:'正常'
      },{
        value:'0',
        label:'下架'
      },{
        value:'-1',
        label:'已过期'
      }],
      input2:'',
      discounts:[{//优惠卷
        value:'1',
        label:'满减卷'
      }],
     // 分页
      paging:{
        title:'',
        type: '',
        status: '',
        currentPage: 1,//当前的默认的页数
        eachpage: 10,//默认的页码
        total: 0,//初始值共数据条
        totalPageNo: 1,
      },
      listData:[],//初始化数据
      dialogFormVisible:false,
      FormVisible: false, //弹窗口
      select:[],//选中的权限'
      rules:[],
      authoriId:'',
      // 弹框
      titleMap: {
        addEquipment:'新增',            
        editEquipment: "编辑"            
     },
     //  输入框宽度
     formLabelWidth: '120px',
    //  输入框所有值
     ruleForm:{
        type:"",
        title:'',
        name:"",
        status:1,
        description:"",
        total:"",
        limit:'',
        discount:'',
        min:"",
        categoryTitle:'',
        time:'',
        categoryId:'',
        gmtEnd:"",
        gmtStart:"",
        days:""
     },//输入框验证
      rules:{
         title:[
           { required: true, message: '说明不能为空', trigger: 'blur' }
        ],
         total:[
           { required: true, message: '优惠券标题不能为空', trigger: 'blur' },
           {required: true,pattern:/^[1-9][0-9]*$/,message: '请输入整数！',trigger: 'blur'}
        ],
        limit:[
           { required: true, message: '优惠卷限领不能为空', trigger: 'blur' },
           {required: true,pattern:/^[1-9][0-9]*$/,message: '请输入整数！',trigger: 'blur'}
        ],
        discount:[
           { required: true, message: '优惠券折扣金额不能为空', trigger: 'blur' },
           {required: true,pattern:/^[1-9][0-9]*$/,message: '请输入整数！',trigger: 'blur'}
        ],
        min:[
           { required: true, message: '优惠券使用门栏不能为空', trigger: 'blur' },
           {required: true,pattern:/^[1-9][0-9]*$/,message: '请输入整数！',trigger: 'blur'}
        ]
      },
     dialogStatus:"",
     compileId:'',//商品id
    }
  },
  //  过滤器
  filters: {
     //   时间戳转换时间格式
      formatDate: function (value) {
        let date = new Date(value);
        let y = date.getFullYear();
        let MM = date.getMonth() + 1;
        MM = MM < 10 ? ('0' + MM) : MM;
        let d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        let h = date.getHours();
        h = h < 10 ? ('0' + h) : h;
        let m = date.getMinutes();
        m = m < 10 ? ('0' + m) : m;
        let s = date.getSeconds();
        s = s < 10 ? ('0' + s) : s;
        return y+'-'+ MM + '-' + d + '-' + h + ':' + m +':'+ s
      },
      categorysTitles:function(value){
          return !value?'全部类目':value
      },
      timeDate:function(value){
        return value=='NaN-NaN-NaN-NaN:NaN:NaN'?'无':value
      },
      gmtStarts:function(value,time){//当前时间小于本地时间就显示已过期否则就现在下架正常
         return time<new Date().getTime()?'已过期':value==0?'下架':'正常'
      }
  },
  created() {
    this.role(),
    this.spUcategory()
  },
  methods: {
    // 切换按钮
    conceals(){
      this.conceal=!this.conceal
    },// 切换按钮
    concealList(){
      this.conceallist=!this.conceallist
    },
    // 分页负值
    handles(val) {
      this.allPages = val;
      this.role();
    },
    //数据详情
      role(){
        let _this=this
        Couponmanage.couponmanage(_this.paging).then(res=>{
            console.log(res)
            _this.listData=res.data.data.items
            // 分页数据
            _this.paging.currentPage=res.data.data.pageNo
            _this.paging.eachpage=res.data.data.pageSize
            _this.paging.total=res.data.data.total
            _this.paging.totalPageNo=res.data.data.totalPageNo
              for (let i = 0; i < _this.listData.length; i++) {//判断是否已过期
                  if (_this.listData[i].gmtEnd<new Date().getTime()) {
                    _this.listData[i].status=-1
                }
           }
        })
      },
    handleChange(val){//获取spu树id
       this.ruleForm.categoryTitle=val
       this.ruleForm.categoryId=this.$refs.cascader.getCheckedNodes()[0].data.value//获取选中的节点数组
    },
      // SPU树
    spUcategory(){
      Couponmanage.category().then(res=>{
          this.options=res.data.data
      })
    },
    //   删除
    handleDelete(index,row){
        let _this=this
        let id=row.id
      _this.$confirm("此操作将永久删除, 是否继续?", "提示", {
          // 提示框
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(() => {
          Couponmanage.deletes(id).then((res) => {
            _this.$message.success("恭喜你，删除成功");
            _this.role();
          });
        })
    },
    // 导出表格形式
    export2Excel(){
      　require.ensure([], () => {
　　　　　　　　const { export_json_to_excel } = require('../../vendor/Export2Excel');
　　　　　　　　//表格商品名
              const tHeader = ['优惠卷id', '优惠卷名称', '优惠卷类型', '介绍', '优惠卷数量','剩余数量', '每人限领', '满减金额', '最底消费', '状态'];
　　　　　　　　//表格商品id
              const filterVal = ['id','title','type','description','total','surplus','surplus','discount','min','status'];
　　　　　　　　const list = this.listData;//优惠卷列表
　　　　　　　　const data = this.formatJson(filterVal, list);
　　　　　　　　export_json_to_excel(tHeader, data, '优惠卷信息');//列表名称
　　　　　　})
    },
    　formatJson(filterVal, jsonData) {
　　　　　　return jsonData.map(v => filterVal.map(j => v[j]))
　　　　},
// 状态
    freezeActivate(row){
       if (row.status==0) {//判断它的状态来负值
                row.status=1
              } else {
                row.status=0
              }
        if (row.gmtEnd<new Date().getTime()) {
          row.status=-1
          this.$message.error("过期优惠卷，建议删除！");
        } else {
          Couponmanage.status(row).then(res=>{
             if (res.data.errmsg=='成功') {
                 this.$message.success("修改优惠券成功");
             }
          })
        }
    },
      // 添加编辑确认按钮
    affirm(ruleForm) {
      console.log(this.ruleForm)
      //判断ruleForm值是否为空
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
            // 判断dialogStatus是否是addEquipment是就添加
          if (this.dialogStatus == "addEquipment") {
            Couponmanage.addition(this.ruleForm).then((res) => {
              if (res.data.errmsg == "成功") {
                 this.$message.success("恭喜你，添加成功");
              } else {
                 this.$message.error(res.data.errmsg);
              }
              this.role();
            });
            this.dialogFormVisible = false;
          }
            // 判断dialogStatus是否是editEquipment是就编辑
          if (this.dialogStatus == "editEquipment") {
            Couponmanage.compile(this.ruleForm, this.compileId).then((res) => {
              if (res.data.errmsg == "成功") {
                 this.$message.success("恭喜你，更新管理员成功");
              } else {
                this.$message.error(res.data.errmsg);
              }
              this.role();
            });
            this.dialogFormVisible = false;
          }
        } else {
            // 为空提示
          this.$message.error("输入框不能为空！");
          return false;
        }
      });
    },
    // 添加
     addEquipment() {
        this.dialogFormVisible = true;
        this.dialogStatus = 'addEquipment';
        this.ruleForm={},
        this.state = false;//禁止的状态
        this.ruleForm.categoryTitle=''
    },
    // 编辑
      handelEdit(row) {
         this.compileId=row.id
         this.dialogFormVisible = true;
         this.dialogStatus = 'editEquipment';
         this.ruleForm={...row}
         this.state = true;//禁止的状态
         this.conceal=true;
         this.ruleForm.type=row.type==1?'满减卷':'';
         this.ruleForm.status=row.status<0?'已过期':row.status==0?'正常':'下架';
        },
    },
watch:{
    // 去除错误提示
    dialogFormVisible(val){
     if (val == false) {
         this.$refs.ruleForm.clearValidate();
     }
    }
  }
}
</script>
<style scoped>
.role{ 
    line-height: 0px;
    overflow: hidden;
}
/* 添加编辑 */
.el-input{        
    width: 300px;
}
.validtimes{
  color:#ffffff;
  background:#409EFF !important;
}
.validtime_nane{
margin-left: 40%;
padding-top: 10px;
}
.validtime{
  width: 150px;
  height: 40px;
  background:#ffffff;
}
.el-table--scrollable-x .el-table__body-wrapper {
    overflow-x: auto;
}
.el-table{
  width:100%;
}
.el-table::-webkit-scrollbar {
  width: 10px;
  height: 10px;
}
::-webkit-scrollbar-thumb {
  background-color: #a1a3a9;
  border-radius: 5px;
}
.el-form/deep/.el-input__inner{
    width: 300px;
}
.el-form-item__content/deep/.el-select{
 padding-left: 0px !important;
}
>>>.el-form-item__content{
    width: 300px;
    margin-left: 0px !important;
} 
>>>.el-dialog/deep/.el-dialog__header{
    width: 50px;
}
.el-form-item/deep/.el-form-item__error{
    text-indent:8rem
}
/* 分页 */
.block{
    width: 40%;
    padding-top: 20px;
}
/* 字体居中 */
.blue{
    background: #409EFF;
    color: #ffffff;
}
.el-table--enable-row-transition/deep/.el-table__body td {
   text-align: center;
}
.el-table/deep/th.is-sortable {
    cursor: pointer;
    text-align: center;
}
.el-table td, .el-table/deep/th.is-leaf {
    text-align: center;
}
/* 布局 */
.el-card/deep/.box-card{
  height: 50%;
   overflow: hidden;
}
.role-content{
    width: 96%;
    margin: auto;
    overflow: hidden;
}
.el-input{
    width: 200px;
    margin-right: 10px;
}
.role-top{
    width: 1010px;
   line-height: 60px;
}
.box-card{
   overflow: hidden;
}
</style>
